#include <iostream>
#include <stdio.h>
using namespace std;
#include <unistd.h>
#include <errno.h>
#include <string>
#include <vector>

// #define SIZE 5

void Usage()
{
    cout << "The usage: " << endl
         << "\t./processpool n" << endl;
}

class channel
{
public:
    channel(int wfd, int process_pid, const string &name)
        : _wfd(wfd), sub_process_id(process_pid), _name(name)
    {
    }

    void Debug()
    {
        cout << "_wfd: " << _wfd;
        cout << " sub_process_id: " << sub_process_id;
        cout << " _name: " << _name << endl;
    }

    ~channel()
    {
    }

    int GetWfd()
    {
        return _wfd;
    }

    int GetSub_process_id()
    {
        return sub_process_id;
    }

    string GetName()
    {
        return _name;
    }

private:
    int _wfd;
    int sub_process_id;
    string _name;
};

class ProcessPool
{
public:
    ProcessPool(int n)
        : _process_nums(n)
    {
    }

    int MakeChannels()
    {
        // 创建管道 子进程
        for (int i = 0; i < _process_nums; i++)
        {
            int pipefd[2]{0};
            int n = pipe(pipefd);
            if (n == -1)
            {
                cout << "pipe error: " << errno << endl;
                return 1;
            }

            pid_t id = fork();
            if (id == 0)
            {
                // child
                close(pipefd[1]);

                exit(0); // 执行完，把子进程退出
            }

            // father
            close(pipefd[0]);

            _channels.push_back(channel(pipefd[1], id, "channel" + to_string(i)));
        }

        return 0;
    }

    void Debug()
    {
        for (auto channel : _channels)
        {
            channel.Debug();
        }
    }

private:
    int _process_nums;
    vector<channel> _channels;
};

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage();
        return 1;
    }
    int process_nums = stoi(argv[1]);
    if (process_nums <= 0)
    {
        cout << "process nums error" << endl;
        return 1;
    }

    ProcessPool *pool = new ProcessPool(process_nums);
    pool->MakeChannels();

    pool->Debug();

   


    delete pool;

    return 0;
}